import Taro, { Component } from '@tarojs/taro'
import { View, Image, Swiper, SwiperItem, Video } from '@tarojs/components'
import './index.scss'
import lodash from '@/utils/lodash'
import classNames from 'classnames'
import QualitySecurity from '@/assets/images/quality-security.png'
import {FyImg} from "@/components/index";

interface IProps {
  //  视频
  video: any
  //  图片
  images: any
}

/**
 * 商品详情轮播图
 */
export default class GoodsCarousel extends Component<IProps, {}> {
  props: any
  state: any
  prevProps: any

  constructor () {
    super(...arguments)
    this.state = {
      list: [],
      current: 0,
    }
    this.prevProps = {}
  }

  onChangeSwiper(e) {
    const {current} = e.detail
    this.setState({
      current
    })
  }

  //  在组件被装载后立即调用。
  componentDidMount() {
    this.prevProps = lodash.cloneDeep(this.props)
    // console.log(this.prevProps)
    this.getImages(this.prevProps)
  }

  //  在已经装载的组件接收到新属性前调用。
  componentWillReceiveProps(nextProps) {
    // console.log('轮播图：componentWillReceiveProps')
    if (JSON.stringify(this.prevProps) === JSON.stringify(nextProps)) return
    // console.log('轮播图：componentWillReceiveProps-------------------------')
    this.getImages(nextProps)
  }

  //  获取图片
  getImages(nextProps) {
    let { images=[], video } = nextProps
    const list:any = []
    if (video.url && video.poster) {
      list.push({ url: video.url, type: 'video', poster: video.poster })
    }
    images.map(url => {
      list.push({ url })
    })
    this.setState({ list })
    this.prevProps = lodash.cloneDeep(nextProps)
  }

  render() {
    const { list=[], current } = this.state

    // console.log(list)
    const prefixCls = 'goods-carousel'
    return (<View className={prefixCls}>
      <Swiper
        autoplay={list.length > 1}
        // circular
        indicatorDots
        indicatorColor='#fff'
        indicatorActiveColor='#fff'
        className={`${prefixCls}-list`}
        // onChange={this.onChangeSwiper.bind(this)}
      >
        {list.map((i, k) => {
          return (<SwiperItem key={k} className={`${prefixCls}-item`}>
            {
              i.type === 'video' ? (
                <Video src={i.url} poster={i.poster}/>
                ) : (
                <img src={i.url}/>
                // <Image src={i.url} lazyLoad/>
              )
            }
            {k === 0 && <View className='quality-img'>
              <FyImg src={QualitySecurity} />
            </View>}
          </SwiperItem>)
        })}
      </Swiper>
      {/*{list.length > 1 && <View className={`${prefixCls}-dot`}>*/}
      {/*  {list.map((_i, k) => {*/}
      {/*    return <View key={k} className={classNames(`${prefixCls}-dot-item`, current === k && `${prefixCls}-dot--active`)}/>*/}
      {/*  })}*/}
      {/*</View>}*/}
    </View>)
  }
}
